%Determine angle of modulation relative to lattice angle

dfs = [];
Times = [0,10e3];
BinEndPts = sqrt(linspace(0,40^2,40));

% df1 = DataFolder({2017 8 14 43 1 1},[],BinEndPts);
% df2 = DataFolder({2017 8 14 48 1 1},[],BinEndPts);
% Period = 11.9;

% df1 = DataFolder({2017 8 30 67 1 1},[],BinEndPts);
% df2 = DataFolder({2017 8 30 74 1 1},[24],BinEndPts);
% Period = 5.2;

% df1 = DataFolder({2017 8 11 29 1 1},[],BinEndPts);
% df2 = DataFolder({2017 8 11 34 1 1},[],BinEndPts);
% Period = 8.1;

df1 = DataFolder({2017 9 28 14 1 1},[],BinEndPts);
df2 = DataFolder({2017 9 28 15 1 1},[],BinEndPts);
Period = 5.1;

%%
Angles = [65:1:110];

AllFp = zeros(4,length(Angles));
AllErr = zeros(4,length(Angles));
for ii = 1:length(Angles)

        [XPos,CutSum,Unc,Frqs,Ft] = df1.sumDirection(Angles(ii)*pi/180);
        [XPosBg,CutSumBg,UncBg,FrqsBg,FtBg] = df2.sumDirection(Angles(ii)*pi/180);
        
        
        X = XPos;
        Y = CutSum-CutSumBg;
        Err = sqrt(Unc.^2+UncBg.^2);

        X = X(~isnan(Y));
        Err = Err(~isnan(Y));
        Y = Y(~isnan(Y));
        
%         InitP = [1/11.9,0.1,0,0];
        InitP = [1/Period,0.1,0,0];
        FixedP = [0,0,0,0];
        
        [Fp,PN,FFH,SE] = fit1D(X,Y,Err,{'sinusoid1D'},InitP,FixedP);
        AllFp(:,ii) = Fp;
        AllErr(:,ii) = SE;
        
%         
%         XInterp = linspace(min(X),max(X),100);
%         figure;
%         errorbar(X,Y,Err,'ro');
%         hold on;
%         plot(XInterp,FFH(XInterp),'b');
%         grid on;
%         xlabel('Position (Latt Sites)');
%         ylabel('n^s');
end

%display fit results
figure;
%fit amplitudes
AngInitP = [90,10,0.1,0];
AngFixedP = [0,0,0,0];
LowLims = [min(Angles),3,0,-inf];
UpLims = [max(Angles),inf,inf,inf];

XAng = Angles;
YAng = abs(AllFp(2,:));
ErrAng = AllErr(2,:);

XAng = XAng(ErrAng<0.3);
YAng = YAng(ErrAng<0.3);
ErrAng = ErrAng(ErrAng<0.3);
[AngFp,~,AngFFH,AngSE] = fit1D(XAng,YAng,ErrAng,{'gaussian1D'},AngInitP,AngFixedP,LowLims,UpLims);
AngInterp = linspace(min(Angles),max(Angles),100);

subplot(2,2,1)
errorbar(Angles,abs(AllFp(2,:)),AllErr(2,:),'ro');
hold on;
plot(AngInterp,AngFFH(AngInterp),'b');
grid on;
ylabel('Fit Amp')
xlabel('Angle')
ylim([0,0.15]);
title(sprintf('Best Fit Angle = %0.2f +/- %0.2f Deg',AngFp(1),AngSE(1)));

subplot(2,2,2)
errorbar(Angles,1./AllFp(1,:),AllErr(1,:)./AllFp(1,:).^2,'ro');
grid on;
ylabel('Period')
xlabel('Angle')
ylim([0,20]);

subplot(2,2,3)
errorbar(Angles,mod(AllFp(3,:),2*pi),AllErr(3,:),'ro');
grid on;
ylabel('Phase')
xlabel('Angle')

subplot(2,2,4)
errorbar(Angles,AllFp(4,:),AllErr(4,:),'ro');
grid on;
ylabel('Offset')
xlabel('Angle')
ylim([-0.1,0.1]);

suptitle('Determine Angle');

